package com.gulimall.ware.service.impl;

import com.common.constant.WareConstant;
import com.common.to.SkuInfoTo;
import com.common.utils.R;
import com.gulimall.ware.dao.WareSkuDao;
import com.gulimall.ware.entity.WareSkuEntity;
import com.gulimall.ware.feign.ProductFeignService;
import com.gulimall.ware.vo.BackItems;
import com.gulimall.ware.vo.PurchaseMergeVo;
import com.gulimall.ware.entity.PurchaseDetailEntity;
import com.gulimall.ware.vo.PurchaseVo;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;

import com.gulimall.ware.dao.PurchaseDao;
import com.gulimall.ware.entity.PurchaseEntity;
import com.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Resource
    private PurchaseDetailServiceImpl purchaseDetailServiceImp;
    @Resource
    private PurchaseDao purchaseDao;
    @Resource
    private WareSkuServiceImpl wareSkuServiceImpl;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    /**
     * 获取未领取的采购单列表
     * @return
     */
    @Override
    public PageUtils getUnReceiveList(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<PurchaseEntity>().eq("status", WareConstant.PurchaseStatusEnum.NEW_CREATE.getCode())
                .or().eq("status", WareConstant.PurchaseStatusEnum.ASSIGN.getCode());
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void merge(PurchaseMergeVo purchaseMergeVo) {
        Long purchaseId = purchaseMergeVo.getPurchaseId();
        // 1、判断是否对采购单进行新增
        if(purchaseId == null){
            // 如果为空说明新建
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.NEW_CREATE.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }else {
            // 如果不为空就对更新时间进行修改
            // 2、检查采购单是否是新建/已分配状态
            PurchaseEntity purchaseEntity1 = purchaseDao.selectById(purchaseId);
            if(purchaseEntity1.getStatus() != WareConstant.PurchaseStatusEnum.NEW_CREATE.getCode()
                && purchaseEntity1.getStatus() != WareConstant.PurchaseStatusEnum.ASSIGN.getCode()){
                // 如果不为新建或已分配就直接退出
                return ;
            }

            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(purchaseId);
            purchaseEntity.setUpdateTime(new Date());
            this.updateById(purchaseEntity);


            // 2、对采购需求进行批修改
            Long[] items = purchaseMergeVo.getItems();
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> purchaseDetailEntityList = Arrays.asList(items).stream().map(item -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                purchaseDetailEntity.setId(item);
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailsStatusEnum.ASSIGN.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailServiceImp.updateBatchById(purchaseDetailEntityList);
        }
    }

    @Override
    public void received(Long[] purchaseIdArray) {
        // 1、过滤不符合条件的采购单，返回要更新的采购单对象集合
        List<Long> purchaseIdList = Arrays.asList(purchaseIdArray);     // 传过来采购单ID集合
        List<PurchaseEntity> purchaseEntities = baseMapper.selectBatchIds(purchaseIdList);  // 对应采购单的对象集合
        List<PurchaseEntity> updatePurchaseList = purchaseEntities.stream()
                // 过滤不为新建/已分配的采购单
                .filter(purchaseEntity -> purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.NEW_CREATE.getCode()
                        || purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGN.getCode())
                // 为每个对象修改更新时间、状态
                .peek(purchaseEntity -> {
                    purchaseEntity.setUpdateTime(new Date());
                    purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                }).collect(Collectors.toList());

        // 2、修改采购单
        this.updateBatchById(updatePurchaseList);

        // 3、修改这些采购单对应的采购需求状态
        purchaseIdList.forEach(purchaseId->{
            // 获取当前采购单ID对应采购需求集合
            List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseDetailServiceImp.getBaseMapper().selectList(new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id", purchaseId));
            // 遍历操作，修改每个采购需求的状态
            purchaseDetailEntityList.forEach(purchaseDetailEntity -> purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailsStatusEnum.BUYING.getCode()));
            purchaseDetailServiceImp.updateBatchById(purchaseDetailEntityList);
        });

    }

    @Transactional
    @Override
    public void done(PurchaseVo purchaseVo) {
        // 1、改变采购需求状态
        List<BackItems> itemList = purchaseVo.getItems();
        boolean isFailed = false;   // 用于标记当前采购单是否失败
        for (BackItems item : itemList) {
            // 修改采购需求状态
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item.getItemId());
            purchaseDetailEntity.setStatus(item.getStatus());
            purchaseDetailServiceImp.updateById(purchaseDetailEntity);
            // 2 判断是否添加仓储
            if(item.getStatus() == WareConstant.PurchaseDetailsStatusEnum.ERROR.getCode()){
                // 如果采购失败，那么就将采购单状态 boolean 值设为失败
                isFailed = true;
            }else{
                // 如果成功，就对仓储进行添加
                PurchaseDetailEntity purchaseDetail = purchaseDetailServiceImp.getById(item.getItemId());
                wareSkuServiceImpl.addStock(purchaseDetail.getSkuId(),purchaseDetail.getWareId(),purchaseDetail.getSkuNum());
            }
        }
        // 3、 对采购表的状态进行修改
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setStatus(isFailed?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.ERROR.getCode());
        purchaseEntity.setId(purchaseVo.getId());
        baseMapper.updateById(purchaseEntity);
    }

}